package com.learn.security.browser;

import com.learn.security.browser.support.SimpleResponse;
import com.learn.security.browser.support.SocialUserInfo;
import com.learn.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 配置默认登录返回值
 */
@RestController
public class BrowserSecurityController {

    Logger logger = LoggerFactory.getLogger(getClass());

    // 请求缓存请求对象
    private RequestCache requestCache = new HttpSessionRequestCache();

    // 请求转发策略对象
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    // core包下管理可配置属性的对象
    @Autowired
    private SecurityProperties securityProperties;


    @Resource
    private ProviderSignInUtils providerSignInUtils;

    /**
     * 包装 默认登录页面
     * 实现功能
     *      1：是html请求，返回默认登录页面
     *      2：如果不是，返回json
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request,response);

        if(null != savedRequest){
            String targetUrl = savedRequest.getRedirectUrl();
            logger.info("引发跳转的url：" + targetUrl);

            if (StringUtils.endsWithIgnoreCase(targetUrl,"html")) {
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
            }
        }

        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }

    @GetMapping("/social/user")
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request){
        SocialUserInfo userInfo = new SocialUserInfo();
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        userInfo.setProviderId(connection.getKey().getProviderId());
        userInfo.setProviderUserId(connection.getKey().getProviderUserId());
        userInfo.setNickName(connection.getDisplayName());
        userInfo.setHeadImg(connection.getImageUrl());
        return userInfo;
    }
}
